/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * DialogVenta.java
 *
 * Created on 17/03/2011, 05:01:46 PM
 */

package com.catosist.run.application.venta;

import com.catosist.run.application.Util.ExcepcionFecha;
import com.catosist.run.application.venta.comprobantedetalle.DialogComprobanteDetalle;
import com.catosist.run.application.venta.guia.ManGuia;
import com.catosist.run.application.viaje.factura.ManFactura;
import com.catosist.run.business.gestorComprobanteDetalle.GestorComprobanteDetalle;
import com.catosist.run.business.gestorConstante.GestorConstante;
import com.catosist.run.business.gestorcliente.GestorCliente;
import com.catosist.run.business.gestorcomprobante.GestorComprobante;
import com.catosist.run.business.gestorviaje.GestorViaje;
import com.catosist.run.services.ClienteDTO;
import com.catosist.run.services.ComprobanteDTO;
import com.catosist.run.services.ComprobanteDetalleDTO;
import java.text.DecimalFormat;
import java.util.Iterator;
import java.util.List;
import java.util.StringTokenizer;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.dao.DataIntegrityViolationException;

/**
 *
 * @author igorov
 */
public class DialogVenta extends javax.swing.JDialog {

    /** Creates new form DialogVenta */
    public DialogVenta(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();

    }

    public DialogVenta(java.awt.Frame parent, boolean modal, GestorComprobante gestorComprobante,
                        GestorCliente gestorCliente, int facturaId,
                        GestorViaje gestorViaje,
                        GestorComprobanteDetalle gestorComprobanteDetalle,
                        GestorConstante gestorConstante) {
        super(parent, modal);
//        tipoComprobante = "factura";
        
        initComponents();
        iniciar();
//        comprobanteDTO = new ComprobanteDTO()
        this.gestorComprobante = gestorComprobante;
        this.gestorComprobanteDetalle = gestorComprobanteDetalle;
        this.gestorConstante = gestorConstante;
        this.gestorCliente = gestorCliente;

        this.gestorViaje = gestorViaje;

        comprobanteDTO = new ComprobanteDTO();
        IGV = gestorConstante.getById(igvId).getPorcentaje();
        DETRACCION = gestorConstante.getById(detraccionId).getPorcentaje();
        
        if(gestorComprobante == null || gestorComprobanteDetalle == null||
                gestorConstante == null || gestorCliente == null ||
                gestorViaje == null)
            System.out.println("NULO!!!!!!!!!!!!!");
        else System.out.println("NO NULO!!!!!!!!");
        this.comprobanteId = facturaId;

        DefaultComboBoxModel modelCmbCliente = new DefaultComboBoxModel();
        modelCmbCliente.addElement("");
        for (Iterator<ClienteDTO> it = gestorCliente.getAll().iterator(); it.hasNext();) {
            ClienteDTO clienteDTO = it.next();
            modelCmbCliente.addElement(clienteDTO.getNombre());
        }
        this.cmbCliente.setModel(modelCmbCliente);

        chkCancelado.setSelected(false);
        mostrarOcultarFechaCancelacion();
        llenar_datos();
        refresh();

    }

    public void iniciar() {
//        ctx = new ClassPathXmlApplicationContext("/applicationContext.xml");
//        gestorComprobanteDetalle = (GestorComprobanteDetalle) ctx.getBean("gestorComprobanteDetalle");
        
//        gestorConstante = (GestorConstante) ctx.getBean("gestorConstante");
        
        
    }

    public void refresh() {
        lista_comprobantes = gestorComprobanteDetalle.getByComprobanteId(comprobanteId);
        model = new DefaultTableModel();

        model.addColumn("ID");
        model.addColumn("Cantidad");
        model.addColumn("Producto");
        model.addColumn("Precio Unitario");
        model.addColumn("Total");

        for (Iterator<ComprobanteDetalleDTO> it = lista_comprobantes.iterator(); it.hasNext();) {
                ComprobanteDetalleDTO comprobanteDetalleDTO = it.next();
                model.addRow(comprobanteDetalleDTO.toArray());
//                total += comprobanteDTO.getTotal();
        }
        this.jTable1.setModel(model);

//        llenar_datos();

    }

    public void llenar_datos(){
        if (comprobanteId != 0) {
            comprobanteDTO = (ComprobanteDTO) gestorComprobante.getById(comprobanteId);

            int indice = -1;
            String tipo = comprobanteDTO.getTipo_comprobante();
            if (tipo.compareTo("f") == 0) {
                indice = 0;
            } else if (tipo.compareTo("b") == 0) {
                indice = 1;
            } else {
                indice = 2;
            }

            cmbTipo.setSelectedIndex(indice);
            String numeroserie = String.valueOf(comprobanteDTO.getNumeroserie());
            String numero = String.valueOf(comprobanteDTO.getNumero());
            String numerorestante = numero.substring(numero.indexOf(numeroserie) + numeroserie.length());
            txtNumeroFactura.setText(numeroserie + "-" + numerorestante);
            System.out.println("Id del cliente: " + comprobanteDTO.getClienteId());
            System.out.println("Idex of "+gestorCliente.getIndexOf(comprobanteDTO.getClienteId()));
            cmbCliente.setSelectedIndex(gestorCliente.getIndexOf(comprobanteDTO.getClienteId()) + 1);

            txtDireccion.setText(comprobanteDTO.getDireccionCliente());
            txtRUC.setText(String.valueOf(comprobanteDTO.getRUCCliente()));
//            txtNombre.setText(comprobanteDTO.getNombreCliente());
            dtcFecha.setDate(comprobanteDTO.getFingreso());
            lblMonto.setText(String.valueOf(comprobanteDTO.getMonto()));
            lblValorSinDetraccion.setText(String.valueOf(comprobanteDTO.getTotalsindetraccion()));
            lblIGV.setText(String.valueOf(comprobanteDTO.getIgv()));
            lblDetraccion.setText(formatearDecimal(comprobanteDTO.getDetraccion()));
            lblMonto.setText(formatearDecimal(comprobanteDTO.getMonto()));
            lblIGV.setText(formatearDecimal(comprobanteDTO.getIgv()));
            lblValorSinDetraccion.setText(formatearDecimal(comprobanteDTO.getTotalsindetraccion()));
            lblTotal.setText(formatearDecimal(comprobanteDTO.getTotal()));
            btnGuias.setEnabled(comprobanteDTO.getViaje() != -1);

            //Para la fecha de cancelacion
            chkCancelado.setSelected(comprobanteDTO.getFcancelacion() != null);
            mostrarOcultarFechaCancelacion();
            if (!chkCancelado.isSelected()) {
                txtAdelanto.setText(String.valueOf(comprobanteDTO.getAdelanto()));
            }
        }
    }


    public void guardarComprobante() {
        //Guardando el comprobante

//        ComprobanteDTO comprobanteDTO = new ComprobanteDTO();
        try {
            String[] tiposComprobantes = {"f", "b", "c"};

            comprobanteDTO.setTipo_comprobante(tiposComprobantes[cmbTipo.getSelectedIndex()]);
            comprobanteDTO.setId(comprobanteId);
            System.out.println("indice seleccionado: " + (cmbCliente.getSelectedIndex() - 1));
            comprobanteDTO.setClienteId(gestorCliente.getIdAtIndex(cmbCliente.getSelectedIndex() - 1));
    //        comprobanteDTO.setClienteId(Integer.parseInt(this.jTable1.getValueAt(this.jTable1.getSelectedRow(),0).toString()));
            comprobanteDTO.setFingreso(dtcFecha.getDate());


            String entradaNumero = txtNumeroFactura.getText().trim();
            String[] tokens_string = new String[2];
            int i = 0;
            StringTokenizer tokens = new StringTokenizer(entradaNumero,"-");
            while(tokens.hasMoreTokens()){
                tokens_string[i++] = tokens.nextToken();
            }

            int numeroserie = Integer.valueOf(tokens_string[0].trim());
            int numerocomprobante = Integer.valueOf(tokens_string[0].trim() + tokens_string[1].trim());

            comprobanteDTO.setNumeroserie(numeroserie);
            comprobanteDTO.setNumero(numerocomprobante);
            
            if (chkCancelado.isSelected()) {
                compararFechas();
                comprobanteDTO.setFcancelacion(dtcFechaCancelado.getDate());
                
            }
            else{
                comprobanteDTO.setFcancelacion(null);
                if(txtAdelanto.getText().length() != 0){
                    Float adelanto = Float.parseFloat(txtAdelanto.getText());
                    adelanto = Float.valueOf((float) Math.round(adelanto * 100)/100);
                    comprobanteDTO.setAdelanto(adelanto);
                }
            }
                

            gestorComprobante.saveOrUpdate(comprobanteDTO);

            if (comprobanteId == 0) {
                comprobanteId = gestorComprobante.getIdByNumero(comprobanteDTO.getNumero());
            }
        } catch (ExcepcionFecha e) {
            JOptionPane.showMessageDialog(this, "La fecha de cancelado no puede ser anterior a la fecha de creacion del comprobante", "Advertencia", JOptionPane.WARNING_MESSAGE);
        }
        catch (NullPointerException e) {
            JOptionPane.showMessageDialog(this, "Formato de entrada de datos incorrecto", "Advertencia", JOptionPane.WARNING_MESSAGE);
        }
    }

    private void compararFechas() throws ExcepcionFecha{
        if (dtcFechaCancelado.getDate().compareTo(dtcFecha.getDate()) == -1) {
                    throw new ExcepcionFecha();
        }
    }

    private String formatearDecimal(Float numero){
        return new DecimalFormat("0.00").format(numero);
    }

    private boolean camposCompletos(){
        if(txtNumeroFactura.getText().length() != 0 &&
           txtDireccion.getText().length() != 0 &&
           txtRUC.getText().length() != 0)
                return true;
        else  return false;
    }

    private void mostrarOcultarFechaCancelacion(){
        lblTitleCancelacion.setVisible(chkCancelado.isSelected());
        dtcFechaCancelado.setVisible(chkCancelado.isSelected());
        lblAdelanto.setVisible(!chkCancelado.isSelected());
        txtAdelanto.setVisible(!chkCancelado.isSelected());
    }

    public String getTipoComprobante() {
        return String.valueOf(cmbTipo.getSelectedItem());
    }
    
    private Float[] calcularDatosComprobante(Float nuevomonto){
        //valores[igv, subtotal, detraccion, total]
        Float[] valores = new Float[4];

        Float igv;
        if(comprobanteDTO.getTipo_comprobante().compareTo("f") == 0)
            igv = IGV * nuevomonto;
        else igv = 0f;

        igv = Float.valueOf((float) Math.round(igv * 100)/100);
        Float totalsindetraccion = nuevomonto + igv;
        Float detraccion;
        if (totalsindetraccion >= 400 && comprobanteDTO.getTipo_comprobante().compareTo("f") == 0) {
            detraccion = DETRACCION * totalsindetraccion;
        }
        else
            detraccion = 0f;
        Float total = totalsindetraccion - detraccion;

        valores[0] = igv;
        valores[1] = totalsindetraccion;
        valores[2] = detraccion;
        valores[3] = total;
        return valores;
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        txtNumeroFactura = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        dtcFecha = new com.toedter.calendar.JDateChooser("yyyy/MM/dd", "####/##/##", '_');
        jLabel3 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        txtDireccion = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        txtRUC = new javax.swing.JTextField();
        jLabel7 = new javax.swing.JLabel();
        lblMonto = new javax.swing.JLabel();
        btnAddItem = new javax.swing.JButton();
        btnEliminarItem = new javax.swing.JButton();
        btnGuardarFactura = new javax.swing.JButton();
        btnGuias = new javax.swing.JButton();
        jButton1 = new javax.swing.JButton();
        lblIGV = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        lblDetraccion = new javax.swing.JLabel();
        jLabel9 = new javax.swing.JLabel();
        lblTotal = new javax.swing.JLabel();
        jLabel10 = new javax.swing.JLabel();
        jLabel11 = new javax.swing.JLabel();
        lblValorSinDetraccion = new javax.swing.JLabel();
        jLabel12 = new javax.swing.JLabel();
        cmbTipo = new javax.swing.JComboBox();
        btnViajes = new javax.swing.JButton();
        cmbCliente = new javax.swing.JComboBox();
        chkCancelado = new javax.swing.JCheckBox();
        lblTitleCancelacion = new javax.swing.JLabel();
        dtcFechaCancelado = new com.toedter.calendar.JDateChooser("yyyy/MM/dd", "####/##/##", '_');
        lblAdelanto = new javax.swing.JLabel();
        txtAdelanto = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setName("Form"); // NOI18N

        jPanel1.setName("jPanel1"); // NOI18N

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(com.catosist.run.application.desktopapplication.DesktopApplication.class).getContext().getResourceMap(DialogVenta.class);
        jLabel1.setFont(resourceMap.getFont("jLabel1.font")); // NOI18N
        jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
        jLabel1.setName("jLabel1"); // NOI18N

        txtNumeroFactura.setName("txtNumeroFactura"); // NOI18N
        txtNumeroFactura.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                txtNumeroFacturaFocusLost(evt);
            }
        });

        jLabel2.setFont(resourceMap.getFont("jLabel2.font")); // NOI18N
        jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N
        jLabel2.setName("jLabel2"); // NOI18N

        dtcFecha.setDate(new java.util.Date());
        dtcFecha.setName("dtcFecha"); // NOI18N
        dtcFecha.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                dtcFechaFocusLost(evt);
            }
        });

        jLabel3.setFont(resourceMap.getFont("jLabel3.font")); // NOI18N
        jLabel3.setText(resourceMap.getString("jLabel3.text")); // NOI18N
        jLabel3.setName("jLabel3"); // NOI18N

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jTable1.setName("jTable1"); // NOI18N
        jScrollPane1.setViewportView(jTable1);

        jLabel4.setText(resourceMap.getString("jLabel4.text")); // NOI18N
        jLabel4.setName("jLabel4"); // NOI18N

        jLabel5.setFont(resourceMap.getFont("jLabel5.font")); // NOI18N
        jLabel5.setText(resourceMap.getString("jLabel5.text")); // NOI18N
        jLabel5.setName("jLabel5"); // NOI18N

        txtDireccion.setEnabled(false);
        txtDireccion.setName("txtDireccion"); // NOI18N
        txtDireccion.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                txtDireccionFocusLost(evt);
            }
        });

        jLabel6.setFont(resourceMap.getFont("jLabel6.font")); // NOI18N
        jLabel6.setText(resourceMap.getString("jLabel6.text")); // NOI18N
        jLabel6.setName("jLabel6"); // NOI18N

        txtRUC.setEnabled(false);
        txtRUC.setName("txtRUC"); // NOI18N
        txtRUC.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                txtRUCFocusLost(evt);
            }
        });

        jLabel7.setFont(resourceMap.getFont("jLabel7.font")); // NOI18N
        jLabel7.setText(resourceMap.getString("jLabel7.text")); // NOI18N
        jLabel7.setName("jLabel7"); // NOI18N

        lblMonto.setFont(resourceMap.getFont("lblIGV.font")); // NOI18N
        lblMonto.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        lblMonto.setText(resourceMap.getString("lblMonto.text")); // NOI18N
        lblMonto.setName("lblMonto"); // NOI18N

        btnAddItem.setText(resourceMap.getString("btnAddItem.text")); // NOI18N
        btnAddItem.setName("btnAddItem"); // NOI18N
        btnAddItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAddItemActionPerformed(evt);
            }
        });

        btnEliminarItem.setText(resourceMap.getString("btnEliminarItem.text")); // NOI18N
        btnEliminarItem.setName("btnEliminarItem"); // NOI18N
        btnEliminarItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEliminarItemActionPerformed(evt);
            }
        });

        btnGuardarFactura.setText(resourceMap.getString("btnGuardarFactura.text")); // NOI18N
        btnGuardarFactura.setName("btnGuardarFactura"); // NOI18N
        btnGuardarFactura.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnGuardarFacturaActionPerformed(evt);
            }
        });

        btnGuias.setText(resourceMap.getString("btnGuias.text")); // NOI18N
        btnGuias.setEnabled(false);
        btnGuias.setName("btnGuias"); // NOI18N
        btnGuias.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnGuiasActionPerformed(evt);
            }
        });

        jButton1.setText(resourceMap.getString("jButton1.text")); // NOI18N
        jButton1.setName("jButton1"); // NOI18N
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        lblIGV.setFont(resourceMap.getFont("lblIGV.font")); // NOI18N
        lblIGV.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        lblIGV.setText(resourceMap.getString("lblIGV.text")); // NOI18N
        lblIGV.setName("lblIGV"); // NOI18N

        jLabel8.setFont(resourceMap.getFont("jLabel8.font")); // NOI18N
        jLabel8.setText(resourceMap.getString("jLabel8.text")); // NOI18N
        jLabel8.setName("jLabel8"); // NOI18N

        lblDetraccion.setFont(resourceMap.getFont("lblDetraccion.font")); // NOI18N
        lblDetraccion.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        lblDetraccion.setText(resourceMap.getString("lblDetraccion.text")); // NOI18N
        lblDetraccion.setName("lblDetraccion"); // NOI18N

        jLabel9.setFont(resourceMap.getFont("jLabel9.font")); // NOI18N
        jLabel9.setText(resourceMap.getString("jLabel9.text")); // NOI18N
        jLabel9.setName("jLabel9"); // NOI18N

        lblTotal.setFont(resourceMap.getFont("lblTotal.font")); // NOI18N
        lblTotal.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        lblTotal.setText(resourceMap.getString("lblTotal.text")); // NOI18N
        lblTotal.setName("lblTotal"); // NOI18N

        jLabel10.setFont(resourceMap.getFont("jLabel10.font")); // NOI18N
        jLabel10.setText(resourceMap.getString("jLabel10.text")); // NOI18N
        jLabel10.setName("jLabel10"); // NOI18N

        jLabel11.setFont(resourceMap.getFont("jLabel11.font")); // NOI18N
        jLabel11.setText(resourceMap.getString("jLabel11.text")); // NOI18N
        jLabel11.setName("jLabel11"); // NOI18N

        lblValorSinDetraccion.setFont(resourceMap.getFont("lblDetraccion.font")); // NOI18N
        lblValorSinDetraccion.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        lblValorSinDetraccion.setText(resourceMap.getString("lblValorSinDetraccion.text")); // NOI18N
        lblValorSinDetraccion.setName("lblValorSinDetraccion"); // NOI18N

        jLabel12.setFont(resourceMap.getFont("jLabel12.font")); // NOI18N
        jLabel12.setText(resourceMap.getString("jLabel12.text")); // NOI18N
        jLabel12.setName("jLabel12"); // NOI18N

        cmbTipo.setFont(resourceMap.getFont("cmbTipo.font")); // NOI18N
        cmbTipo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Factura", "Boleta", "Contrato al Cliente" }));
        cmbTipo.setName("cmbTipo"); // NOI18N
        cmbTipo.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                cmbTipoItemStateChanged(evt);
            }
        });

        btnViajes.setText(resourceMap.getString("btnViajes.text")); // NOI18N
        btnViajes.setName("btnViajes"); // NOI18N
        btnViajes.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnViajesActionPerformed(evt);
            }
        });

        cmbCliente.setFont(resourceMap.getFont("cmbCliente.font")); // NOI18N
        cmbCliente.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        cmbCliente.setName("cmbCliente"); // NOI18N
        cmbCliente.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                cmbClienteItemStateChanged(evt);
            }
        });

        chkCancelado.setFont(resourceMap.getFont("chkCancelado.font")); // NOI18N
        chkCancelado.setText(resourceMap.getString("chkCancelado.text")); // NOI18N
        chkCancelado.setName("chkCancelado"); // NOI18N
        chkCancelado.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                chkCanceladoActionPerformed(evt);
            }
        });

        lblTitleCancelacion.setFont(resourceMap.getFont("lblTitleCancelacion.font")); // NOI18N
        lblTitleCancelacion.setText(resourceMap.getString("lblTitleCancelacion.text")); // NOI18N
        lblTitleCancelacion.setName("lblTitleCancelacion"); // NOI18N

        dtcFechaCancelado.setDate(new java.util.Date());
        dtcFechaCancelado.setName("dtcFechaCancelado"); // NOI18N
        dtcFechaCancelado.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                dtcFechaCanceladoFocusLost(evt);
            }
        });

        lblAdelanto.setFont(resourceMap.getFont("lblAdelanto.font")); // NOI18N
        lblAdelanto.setText(resourceMap.getString("lblAdelanto.text")); // NOI18N
        lblAdelanto.setName("lblAdelanto"); // NOI18N

        txtAdelanto.setFont(resourceMap.getFont("txtAdelanto.font")); // NOI18N
        txtAdelanto.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
        txtAdelanto.setText(resourceMap.getString("txtAdelanto.text")); // NOI18N
        txtAdelanto.setName("txtAdelanto"); // NOI18N

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 754, Short.MAX_VALUE)
                    .addComponent(jLabel4, javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addComponent(jLabel3)
                            .addComponent(jLabel5)
                            .addComponent(jLabel6))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(cmbCliente, 0, 626, Short.MAX_VALUE)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(txtNumeroFactura, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(71, 71, 71)
                                .addComponent(jLabel12)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(cmbTipo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 70, Short.MAX_VALUE)
                                .addComponent(jLabel2)
                                .addGap(3, 3, 3)
                                .addComponent(dtcFecha, javax.swing.GroupLayout.PREFERRED_SIZE, 118, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(txtDireccion, javax.swing.GroupLayout.DEFAULT_SIZE, 626, Short.MAX_VALUE)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                                .addComponent(txtRUC, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(87, 87, 87)
                                .addComponent(chkCancelado)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 42, Short.MAX_VALUE)
                                .addComponent(lblTitleCancelacion)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(dtcFechaCancelado, javax.swing.GroupLayout.PREFERRED_SIZE, 118, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                                .addComponent(lblAdelanto)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(txtAdelanto, javax.swing.GroupLayout.PREFERRED_SIZE, 95, javax.swing.GroupLayout.PREFERRED_SIZE))))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
                        .addGap(166, 166, 166)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(btnViajes)
                            .addComponent(btnAddItem)
                            .addComponent(btnGuardarFactura, javax.swing.GroupLayout.PREFERRED_SIZE, 94, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(btnEliminarItem)
                                    .addComponent(btnGuias))
                                .addGap(80, 80, 80)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addGroup(jPanel1Layout.createSequentialGroup()
                                        .addComponent(jLabel7)
                                        .addGap(3, 3, 3))
                                    .addGroup(jPanel1Layout.createSequentialGroup()
                                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                            .addComponent(jLabel8)
                                            .addComponent(jLabel11)
                                            .addComponent(jLabel9))
                                        .addGap(7, 7, 7))
                                    .addComponent(jLabel10, javax.swing.GroupLayout.Alignment.TRAILING))
                                .addGap(18, 18, 18)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(lblDetraccion, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 111, Short.MAX_VALUE)
                                    .addComponent(lblTotal, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 111, Short.MAX_VALUE)
                                    .addComponent(lblMonto, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 111, Short.MAX_VALUE)
                                    .addComponent(lblValorSinDetraccion, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 111, Short.MAX_VALUE)
                                    .addComponent(lblIGV, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 111, Short.MAX_VALUE)))
                            .addComponent(jButton1))))
                .addGap(57, 57, 57))
        );

        jPanel1Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {btnGuias, btnViajes});

        jPanel1Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {btnAddItem, btnEliminarItem});

        jPanel1Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {btnGuardarFactura, jButton1});

        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel1)
                        .addComponent(txtNumeroFactura, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel12)
                        .addComponent(cmbTipo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jLabel2)
                    .addComponent(dtcFecha, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(cmbCliente, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(txtDireccion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel6)
                        .addComponent(txtRUC, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(chkCancelado)
                        .addComponent(lblTitleCancelacion))
                    .addComponent(dtcFechaCancelado, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel4)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(txtAdelanto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(lblAdelanto)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 288, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jLabel7)
                                .addGap(3, 3, 3)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                    .addComponent(jLabel8)
                                    .addComponent(lblIGV, javax.swing.GroupLayout.PREFERRED_SIZE, 15, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                    .addComponent(jLabel11)
                                    .addComponent(lblValorSinDetraccion, javax.swing.GroupLayout.PREFERRED_SIZE, 15, javax.swing.GroupLayout.PREFERRED_SIZE)))
                            .addComponent(lblMonto))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(lblDetraccion, javax.swing.GroupLayout.PREFERRED_SIZE, 15, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel9)
                            .addComponent(btnViajes)
                            .addComponent(btnGuias)))
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(btnAddItem)
                        .addComponent(btnEliminarItem)))
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(12, 12, 12)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel10)
                            .addComponent(lblTotal, javax.swing.GroupLayout.PREFERRED_SIZE, 15, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(29, 29, 29)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(btnGuardarFactura)
                            .addComponent(jButton1))))
                .addContainerGap(23, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void txtNumeroFacturaFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtNumeroFacturaFocusLost
        // TODO add your handling code here:
    }//GEN-LAST:event_txtNumeroFacturaFocusLost

    private void dtcFechaFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_dtcFechaFocusLost
        //        this.cmbDescripcion.requestFocus();
}//GEN-LAST:event_dtcFechaFocusLost

    private void txtDireccionFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtDireccionFocusLost
        // TODO add your handling code here:
    }//GEN-LAST:event_txtDireccionFocusLost

    private void txtRUCFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtRUCFocusLost

}//GEN-LAST:event_txtRUCFocusLost

    private void btnAddItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddItemActionPerformed
        // TODO add your handling code here:
        try {
            if (camposCompletos()) {
                //Guardando los datos de la factura
                guardarComprobante();
                DialogComprobanteDetalle dialogComprobanteDetalle = new DialogComprobanteDetalle(this, true, comprobanteId);
                dialogComprobanteDetalle.setLocationRelativeTo(this);
                dialogComprobanteDetalle.setVisible(true);
                //        System.out.println("Objeto: " + dialogFacturaDetalle.getObjeto());
                //            totalComprobante += dialogFacturaDetalle.getComprobanteDetalleDTO().getTotal();
                //            lista_comprobantes.add(dialogFacturaDetalle.getComprobanteDetalleDTO());

                Float montoactual = comprobanteDTO.getMonto();

                if (dialogComprobanteDetalle.getComprobanteDetalleDTO() != null) {
                    Float nuevomonto = montoactual + dialogComprobanteDetalle.getComprobanteDetalleDTO().getTotal();
                    
//                    Float igv;
//                    if(comprobanteDTO.getTipo_comprobante().compareTo("f") == 0)
//                        igv = IGV * nuevomonto;
//                    else igv = 0f;
//
//                    igv = Float.valueOf((float) Math.round(igv * 100)/100);
//                    Float totalsindetraccion = nuevomonto + igv;
//                    Float detraccion;
//                    if (totalsindetraccion >= 400 && comprobanteDTO.getTipo_comprobante().compareTo("f") == 0) {
//                        detraccion = DETRACCION * totalsindetraccion;
//                    }
//                    else
//                        detraccion = 0f;
//                    Float total = totalsindetraccion - detraccion;
                    Float[] valoresCalculados = calcularDatosComprobante(nuevomonto);
                    comprobanteDTO.setMonto(nuevomonto);
                    comprobanteDTO.setIgv(valoresCalculados[0]);//comprobanteDTO.setIgv(igv);
                    comprobanteDTO.setTotalsindetraccion(valoresCalculados[1]);//comprobanteDTO.setTotalsindetraccion(totalsindetraccion);
                    comprobanteDTO.setDetraccion(valoresCalculados[2]);//comprobanteDTO.setDetraccion(detraccion);
                    comprobanteDTO.setTotal(valoresCalculados[3]);//comprobanteDTO.setTotal(total);

                    lblMonto.setText(formatearDecimal(nuevomonto));
                    lblIGV.setText(formatearDecimal(comprobanteDTO.getIgv()));
                    lblValorSinDetraccion.setText(formatearDecimal(comprobanteDTO.getTotalsindetraccion()));
                    lblDetraccion.setText(formatearDecimal(comprobanteDTO.getDetraccion()));
                    lblTotal.setText(formatearDecimal(comprobanteDTO.getTotal()));

                    guardarComprobante();
                    refresh();
                }
                
            } else {
                JOptionPane.showMessageDialog(this, "Deben estar llenos todos los campos del comprobante", "Advertencia", JOptionPane.WARNING_MESSAGE);
            }
        } catch (DataIntegrityViolationException e) {
            JOptionPane.showMessageDialog(this, "Ya existe una factura con ese numero", "Advertencia", JOptionPane.WARNING_MESSAGE);
        }
    }//GEN-LAST:event_btnAddItemActionPerformed

    private void btnEliminarItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEliminarItemActionPerformed
        // TODO add your handling code here:
        try {
            //            int i = this.jTable1.getSelectedRow();
            //            System.out.println("Item: " + i);
            //            totalComprobante -= lista_comprobantes.get(i).getTotal();
            //            lista_comprobantes_borrados.add(lista_comprobantes.get(i));
            //            gestorComprobanteDetalle.deleteById(lista_comprobantes.get(i).getId());
            //            lista_comprobantes.remove(i);
            int i = Integer.parseInt(this.jTable1.getValueAt(this.jTable1.getSelectedRow(),0).toString());
            Float precio_eliminado = Float.parseFloat(jTable1.getValueAt(this.jTable1.getSelectedRow(), 4).toString());
            Float nuevomonto = comprobanteDTO.getMonto() - precio_eliminado;

            Float[] valoresCalculados = calcularDatosComprobante(nuevomonto);
            comprobanteDTO.setMonto(nuevomonto);
            comprobanteDTO.setIgv(valoresCalculados[0]);//comprobanteDTO.setIgv(igv);
            comprobanteDTO.setTotalsindetraccion(valoresCalculados[1]);//comprobanteDTO.setTotalsindetraccion(totalsindetraccion);
            comprobanteDTO.setDetraccion(valoresCalculados[2]);//comprobanteDTO.setDetraccion(detraccion);
            comprobanteDTO.setTotal(valoresCalculados[3]);//comprobanteDTO.setTotal(total);

            lblMonto.setText(formatearDecimal(nuevomonto));
            lblIGV.setText(formatearDecimal(comprobanteDTO.getIgv()));
            lblValorSinDetraccion.setText(formatearDecimal(comprobanteDTO.getTotalsindetraccion()));
            lblDetraccion.setText(formatearDecimal(comprobanteDTO.getDetraccion()));
            lblTotal.setText(formatearDecimal(comprobanteDTO.getTotal()));

            gestorComprobanteDetalle.deleteById(i);
            guardarComprobante();
            refresh();


        } catch (Exception e) {
            JOptionPane.showMessageDialog(this, "Debe seleccionar un Item existente", "Advertencia", JOptionPane.WARNING_MESSAGE);
        }
}//GEN-LAST:event_btnEliminarItemActionPerformed

    private void btnGuardarFacturaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGuardarFacturaActionPerformed
        // TODO add your handling code here:
        try {
            guardarComprobante();
            this.setVisible(false);
        } catch (NullPointerException e) {
            JOptionPane.showMessageDialog(this, "Formato de entrada de datos incorrecto", "Advertencia", JOptionPane.WARNING_MESSAGE);
        } 

}//GEN-LAST:event_btnGuardarFacturaActionPerformed

    private void btnGuiasActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGuiasActionPerformed
        // TODO add your handling code here:
        //        List<ComprobanteDetalleDTO> tmp = new LinkedList<ComprobanteDetalleDTO>();
        //        for (int i = 0; i < lista_comprobantes.size(); i++) {
        //            tmp.add(lista_comprobantes.get(i));
        //        }
//        guardar();
//        llenar_datos();
        ManGuia manGuia = new ManGuia(this, true, comprobanteId, lista_comprobantes, gestorComprobanteDetalle);
        manGuia.setLocationRelativeTo(this);
        manGuia.setVisible(true);
        refresh();
}//GEN-LAST:event_btnGuiasActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // TODO add your handling code here:
//        System.out.println("Comprobantes detalles: ");
//        for (int i = 0; i < lista_comprobantes.size(); i++) {
//            ComprobanteDetalleDTO comprobanteDetalleDTO = lista_comprobantes.get(i);
//            System.out.println(comprobanteDetalleDTO.getProducto() + ", id " + comprobanteDetalleDTO.getGuiaId());
//        }
        this.setVisible(false);
    }//GEN-LAST:event_jButton1ActionPerformed

    private void btnViajesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnViajesActionPerformed
        // TODO add your handling code here:
        DialogSeleccionViaje dialogSeleccionViaje = new DialogSeleccionViaje(this, true, comprobanteDTO, gestorViaje);
        dialogSeleccionViaje.setLocationRelativeTo(this);
        dialogSeleccionViaje.setVisible(true);

        btnGuias.setEnabled(comprobanteDTO.getViaje() != -1);

        gestorComprobante.saveOrUpdate(comprobanteDTO);
    }//GEN-LAST:event_btnViajesActionPerformed

    private void cmbClienteItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_cmbClienteItemStateChanged
        // TODO add your handling code here:
        try {
            System.out.println("indice seleccionado "+cmbCliente.getSelectedIndex());
            ClienteDTO clienteDTO = gestorCliente.getByIndex(cmbCliente.getSelectedIndex() - 1);
            txtDireccion.setText(clienteDTO.getDireccion());
            txtRUC.setText(String.valueOf(clienteDTO.getRUC()));
        } catch (Exception e) {
            System.out.println("Excepcion controlada");
            txtDireccion.setText("");
            txtRUC.setText("");
        }

    }//GEN-LAST:event_cmbClienteItemStateChanged

    private void chkCanceladoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_chkCanceladoActionPerformed
        // TODO add your handling code here:
        mostrarOcultarFechaCancelacion();
    }//GEN-LAST:event_chkCanceladoActionPerformed

    private void dtcFechaCanceladoFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_dtcFechaCanceladoFocusLost
        // TODO add your handling code here:
    }//GEN-LAST:event_dtcFechaCanceladoFocusLost

    private void cmbTipoItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_cmbTipoItemStateChanged
        // TODO add your handling code here:
        try {
            Float monto = comprobanteDTO.getMonto();
            Float[] valoresCalculados = calcularDatosComprobante(monto);
                    comprobanteDTO.setMonto(monto);
                    comprobanteDTO.setIgv(valoresCalculados[0]);//comprobanteDTO.setIgv(igv);
                    comprobanteDTO.setTotalsindetraccion(valoresCalculados[1]);//comprobanteDTO.setTotalsindetraccion(totalsindetraccion);
                    comprobanteDTO.setDetraccion(valoresCalculados[2]);//comprobanteDTO.setDetraccion(detraccion);
                    comprobanteDTO.setTotal(valoresCalculados[3]);//comprobanteDTO.setTotal(total);

                    lblMonto.setText(formatearDecimal(monto));
                    lblIGV.setText(formatearDecimal(comprobanteDTO.getIgv()));
                    lblValorSinDetraccion.setText(formatearDecimal(comprobanteDTO.getTotalsindetraccion()));
                    lblDetraccion.setText(formatearDecimal(comprobanteDTO.getDetraccion()));
                    lblTotal.setText(formatearDecimal(comprobanteDTO.getTotal()));

                    guardarComprobante();
            
        } catch (Exception e) {
            System.out.print("Excepcion en dialog venta: " + e.toString());
        }
    }//GEN-LAST:event_cmbTipoItemStateChanged

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                DialogVenta dialog = new DialogVenta(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAddItem;
    private javax.swing.JButton btnEliminarItem;
    private javax.swing.JButton btnGuardarFactura;
    private javax.swing.JButton btnGuias;
    private javax.swing.JButton btnViajes;
    private javax.swing.JCheckBox chkCancelado;
    private javax.swing.JComboBox cmbCliente;
    private javax.swing.JComboBox cmbTipo;
    private com.toedter.calendar.JDateChooser dtcFecha;
    private com.toedter.calendar.JDateChooser dtcFechaCancelado;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel12;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JLabel lblAdelanto;
    private javax.swing.JLabel lblDetraccion;
    private javax.swing.JLabel lblIGV;
    private javax.swing.JLabel lblMonto;
    private javax.swing.JLabel lblTitleCancelacion;
    private javax.swing.JLabel lblTotal;
    private javax.swing.JLabel lblValorSinDetraccion;
    private javax.swing.JTextField txtAdelanto;
    private javax.swing.JTextField txtDireccion;
    private javax.swing.JTextField txtNumeroFactura;
    private javax.swing.JTextField txtRUC;
    // End of variables declaration//GEN-END:variables
    private DefaultTableModel model;
    private List<ComprobanteDetalleDTO> lista_comprobantes;
//    private ApplicationContext ctx;
    private GestorComprobanteDetalle gestorComprobanteDetalle;
    private GestorComprobante gestorComprobante;
    private GestorCliente gestorCliente;
    private GestorConstante gestorConstante;
    private int comprobanteId;
    ComprobanteDTO comprobanteDTO;
//    private String tipoComprobante;
    private Float IGV;
    private Float DETRACCION;
    private final int igvId = 1;
    private final int detraccionId = 2;
//    private int viajeId;
//    ManFactura manFactura;
    private GestorViaje gestorViaje;
}
